<?php
namespace Modules\Activity\Http\Controllers\Client\Lottery;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;

use \Modules\Activity\Entities\Lottery\Activity;
use \Modules\Activity\Entities\ActivityOrder as Order;
use \Modules\User\Entities\User;

use Validator;
use ThrowException;
use Auth;
use DB;


// 一番赏订单
class OrderController extends Controller
{
    // 预览订单
    public function preview(Request $req)
    {
        $rule = [
            'activity_id' => ['required'],
            // 'room_id'
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest(); 

        $user = Auth::requireLoginUser();

        // 活动
        $activity = Activity::getEntity([
            'id' => $req->input('activity_id')
        ]);

        // 是否要求一定要绑定手机号
        if ($activity->is_need_phone && !$user->phone) {
            ThrowException::RequirePhone();
        }

        // 购买数量, 0为全包
        $total = 1;

        // $activity->checkPerUserLimit($user, $total);
        // $skuableMaps = $activity->randomSku($total) ?: ThrowException::Conflict('库存不足~');
        $skuableMaps = [
            [
                'skuable' => $activity,
                'total' => $total
            ]
        ];

        $coupon = NULL;
        if ($req->input('coupon_id'))
            $coupon = $user->coupons()->valid()->where('id', $req->coupon_id)->first();

        $isUseRedpack = $req->input('is_use_redpack');
        $order = Order::initWith($skuableMaps, $user, NULL, [
            'coupon' => $coupon,
            'is_use_redpack' => $isUseRedpack
        ]);

        // 计算可用优惠券
        $coupons = $order->filterCoupons($user->coupons()->with('base_coupon')->valid()->get());
        
        $orderInfo = [
            'redpack' => $order->calcUsableRedpack($user),
            'is_use_redpack' => $isUseRedpack,
            'coupons' => $coupons,
            'carriage' => $order->carriage,
            'coupon_discount' => $order->coupon_discount,
            'product_money_price' => $order->product_money_price,
            'product_score_price' => $order->product_score_price,
            'pay_money_price' => $order->pay_money_price,
            'pay_score_price' => $order->pay_score_price,
        ];

        return [
            'order' => $orderInfo
        ];
    }


    // 创建订单
    public function store(Request $req) {
        $rule = [
            'activity_id' => ['required']
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest(); 

        $user = Auth::requireLoginUser();
        // 1秒内只能调1次此api
        Auth::limitTimeBeforeProcess($user, 'create_order', 1);

        // 活动
        $activity = Activity::getEntity([
            'id' => $req->input('activity_id')
        ]);

        // 是否要求一定要绑定手机号
        if ($activity->is_need_phone && !$user->phone) {
            ThrowException::RequirePhone();
        }

        // 是否要求一定要绑定手机号
        if ($activity->isNeedJoinCode()) {
            $req->input('join_code') || ThrowException::Conflict('请输入参与码~');

            $activity->checkJoinCode($req->join_code) || ThrowException::Conflict('参与码不正确~');
        }

        if ($activity->records()->where('session', $activity->current_session)->where('user_id', $user->id)->first()) {
            ThrowException::Conflict('您已参与过当期活动~');
        }

        // 购买数量, 0为全包
        $total = 1;

        // $activity->checkPerUserLimit($user, $total);
        // $skuableMaps = $activity->randomSku($total) ?: ThrowException::Conflict('库存不足~');
        $skuableMaps = [
            [
                'skuable' => $activity,
                'total' => $total
            ]
        ];

        DB::beginTransaction();

        $coupon = NULL;
        if ($req->input('coupon_id'))
            $coupon = $user->coupons()->valid()->where('id', $req->coupon_id)->first();

        $isUseRedpack = $req->input('is_use_redpack');
        $order = Order::initWith($skuableMaps, $user, NULL, [
            // 'activity' => $activity,
            'node' => $activity,
            'coupon' => $coupon,
            'is_use_redpack' => $isUseRedpack,
            'is_visible' => 0,
            'options' => [
            ]
        ]);

        $order->createAll();

        DB::commit();

        // 返回订单内容
        return $order->generateResponse();
    }

    // 创建订单
    public function try(Request $req, $uuid) {
        $rule = [
            'try_total' => ['required'],
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest(); 

        $user = Auth::requireLoginUser();

        $activity = Activity::getChildrenEntity([
            'uuid' => $uuid
        ]);

        $total = $req->input('try_total') ?: 1;
        $skuableMaps = $activity->randomSku($total) ?: ThrowException::Conflict('库存不足~');

        $skus = [];
        foreach ($skuableMaps as $key => $skuableMap) {
            array_push($skus, OrderSku::initWith($skuableMap['skuable'], $skuableMap['total']));
        }

        return [
            'info' => [
                'skus' => $skus
            ]
        ];
    }

    // 添加一个机器人  /lottery/order/storeJob?activity_id=36
    public function storeJob(Request $req) {
        $rule = [
            'activity_id' => ['required'],
            'user_id' => ['required']
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest();

        // 活动
        $activity = Activity::getEntity([
            'id' => $req->input('activity_id')
        ]);

        $user_id = $req->input('user_id');
        $user =  User::getEntity([
            'id' => $user_id
        ]);

        if ($activity->records()->where('session', $activity->current_session)->where('user_id', $user->id)->first()) {
            ThrowException::Conflict('您已参与过当期活动~');
        }

        // 购买数量, 0为全包
        $total = 1;

        $skuableMaps = [
            [
                'skuable' => $activity,
                'total' => $total
            ]
        ];

        DB::beginTransaction();

        $coupon = NULL;

        $isUseRedpack = $req->input('is_use_redpack');
        $order = Order::initWith($skuableMaps, $user, NULL, [
            // 'activity' => $activity,
            'node' => $activity,
            'coupon' => $coupon,
            'is_use_redpack' => $isUseRedpack,
            'is_visible' => 0,
            'options' => [
            ]
        ]);

        $order->pay_money_price = 0;
        $order->pay_score_price = 0;
        $order->remark = 'job order';
        $order->brokerage_status = 1;
        $order->share_status = 1;
        $this->base_sku = $activity;

        $order->createAll();

        DB::commit();

        // 返回订单内容
        return $order->generateResponse();
    }

    public function getJobUser()
    {
        $options['only'] = [
            'id',
            'name',
            'phone',
            'headimg'
        ];
        $options['where'][] = ['id', '<', 135];

        $list = User::getList($options);

        return $list->generateListResponse();
    }

}
